﻿/*
 * Author：WQ
 * Date：2012/12/25 11:22:38  
 * Copyright：2012-2013 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IPMessenger.Common.Model;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace IPMessenger.Common.Uitls
{
    public class CommonTools
    {
        /// <summary>
        /// 序列化class为byte[]
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static byte[] Serialize<T>(T obj) where T : class
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, obj);
            stream.Position = 0;
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);

            stream.Flush();
            stream.Close();

            return buffer;
        }

        /// <summary>
        /// 序列化byte[]为class
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="newT"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static T Deserialize<T>(T newT, byte[] buffer) where T : class
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(buffer);
            newT = (T)formatter.Deserialize(stream);

            stream.Flush();
            stream.Close();

            return newT;
        }
    }
}
